#include "header.h"
#include "logger.h"
#include "tcpconnection.hpp"
#include "tcpserver.hpp"
#include <iostream>
#include <stdio.h>
#include <unordered_map>
#include <chrono>
using namespace std;
using std::unordered_map;
#define BUFFER_SIZE 1024
struct client_t{//存储建立好的链接的相关消息
    int fd;//存储客户的文件描述符
    time_t last_time;//存储客户的最后一次活跃时间
};
namespace moqi
{

void onConnection(TcpConnectionPtr con)
{
    LOG_INFO(con->status());
}

void onMessage(TcpConnectionPtr con)
{
    string msg = con->recv();
    LOG_INFO(con->status() + " recv " + msg + " <<<");
    //假设执行的回显服务
    string response = msg;
    //send
    con->send(response); 
    LOG_INFO(">>> send " + msg + " to " + con->status());
}
void onClosed(TcpConnectionPtr con)
{
    LOG_INFO(con->status()+" closed");
}

int test()
{
//    const char * sourceIP = "0.0.0.0";
  //  const char * sourcePort = "9031";
    TcpServer server(8080);
    server.setAllConnectionCallback(onConnection, onMessage, onClosed);
    server.start();
    LOG_INFO("server start working");

    return 0;
}
#if 0
TimerFd timefd(1, 2,[&clients, &epoll](){
        cout<<"定时器到时"<<endl;
        int curTime = time(nullptr);
        for(auto client:clients)
        //TO DO//迭代器失效，不能用AutoCode
        {
            if(curTime-client.second > 30)
            {
                int delfd = client.first;
                close(delfd);
                cout << "客户" << "超时踢出" << endl;
                cout << "上次发言时间 ："<< client.second << endl;
                cout << "当前时间： " << curTime << endl;
                clients.erase(delfd);
    //            epoll.del(delfd);
            }
        }
        });
 
    moqi::Thread th(bind(&TimerFd::start, &timefd));
    th.start();
}
#endif
}//end of namespace moqi
 
int main()
{
    moqi::test();
    return 0;
}
